package com.jd.cs.config;

/**
 * @author: lizhiwei
 * @date: 2020-09-03 15:01
 **/

import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static org.hibernate.validator.internal.util.Contracts.assertNotNull;

/**
 * JWT的token，区分大小写
 */
@ConfigurationProperties(prefix = "config.jwt")
@Component
public class JwtConfig {
    private final static Logger logger = LoggerFactory.getLogger(JwtConfig.class);

    private String secret;
    private long expire;
    private String header;
    private String issuer;

    /**
     * 生成token
     *
     * @param payload
     * @return
     */
    public String createToken(Map<String, Object> payload) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expireDate = now.plusSeconds(expire);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setClaims(payload)
                .setIssuer(issuer)
                .setIssuedAt(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()))
                .setExpiration(Date.from(expireDate.atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }


    public Jwt parse(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
    }

    /**
     * 获取token中注册信息
     *
     * @param token
     * @return
     */
    public Claims getTokenClaim(String token) {
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            logger.error("getTokenClaim err", e);
            return null;
        }
    }

    /**
     * 验证token是否过期失效
     *
     * @param expirationTime
     * @return
     */
    public boolean isTokenExpired(Date expirationTime) {
        return expirationTime.before(new Date());
    }

    /**
     * 获取token失效时间
     *
     * @param token
     * @return
     */
    public Date getExpirationDateFromToken(String token) {
        return getTokenClaim(token).getExpiration();
    }

    /**
     * 获取用户名从token中
     */
    public String getUsernameFromToken(String token) {
        return getTokenClaim(token).getSubject();
    }

    /**
     * 获取jwt发布时间
     */
    public Date getIssuedAtDateFromToken(String token) {
        return getTokenClaim(token).getIssuedAt();
    }

    // --------------------- getter & setter ---------------------

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }


    public static void main(String[] args) throws Exception {
        // RSA keyPair Generator
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        /*
         * 长度 至少 1024, 建议 2048
         */
        final int keySize = 2048;
        keyPairGenerator.initialize(keySize);

        final KeyPair keyPair = keyPairGenerator.genKeyPair();

        final PrivateKey privateKey = keyPair.getPrivate();

        // gen id_token
        //final Date exp = DateUtils.addMinutes(new Date(), 5);
        final Date exp = Date.from(LocalDateTime.now().plusMinutes(5).atZone(ZoneId.systemDefault()).toInstant());
        final JwtBuilder jwtBuilder = Jwts.builder().setId("jti").setSubject("sub").setExpiration(exp).signWith(SignatureAlgorithm.RS512, privateKey);
        Map<String, Object> map = new HashMap<>();
        map.put("aaa", "aaa213");
        map.put("bbb", "bbb213");
        jwtBuilder.setClaims(map);
        jwtBuilder.setHeaderParams(map);
        final String idToken = jwtBuilder.compact();


        assertNotNull(idToken);
        System.out.println(idToken);


        // verify

        final PublicKey publicKey = keyPair.getPublic();
//        final Jwt jwt = Jwts.parser().parse(idToken);
        final JwtParser parser = Jwts.parser();
        final Jwt jwt = parser.setSigningKey(publicKey).parse(idToken);

        assertNotNull(jwt);
        System.out.println(jwt.getHeader());
        System.out.println(jwt.getBody());

    }
}